<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>随机小方块</title>
		<style>
			body div:nth-child(2n+1) {
				width: 800px;
				height: 800px;
				background-color: skyblue;
				position: relative;
			}
			/*body div:nth-child(2n) {
				width: 80px;
				height: 40px;
				background-color: pink;
				position: relative;
			}*/
			.C2{
				width: 80px;
				height: 40px;
				background-color: pink;
				position: relative;
			}
			.C1{
				color: green;
			}
		</style>
	</head>

	<body>
		<div class="map">
		</div>
		<!--<div class="C1" id="d2">
			我在这
		</div >-->

		<!--js代码-->
		<script type="text/javascript">
			
			
//			var my$=function(id){
//				return document.getElementById(id);
//			}
//			
//			my$("d2").className="C1 C2";
			//函数的自调用
			(function() {
				var intervalId = setInterval(function() {
					var map = document.querySelector(".map")

					function Food(width, height, color) {
						this.width = width || 20;
						this.height = height || 20;
						this.color = color;
						this.x = 0;
						this.y = 0;
						this.element = document.createElement("div");
					}

					Food.prototype.init = function(map) {
						var div = this.element;
						div.style.width = this.width + "px";
						div.style.height = this.height + "px";
						div.style.backgroundColor = this.color;
						div.style.position = "absolute";
						this.render(map);
						//移除map元素中的第一个子元素
//						if(map.firstChild){
//							map.removeChild(map.firstChild);
//						}
						map.appendChild(div);

					}

					Food.prototype.render = function(map) {
						console.log(map.offsetWidth, this.width);
						var x = Math.floor(Math.random() * map.offsetWidth / this.width) * this.width;
						var y = Math.floor(Math.random() * map.offsetHeight / this.height) * this.height;
						console.log("x", x);
						this.x = x;
						this.y = y;
						var div = this.element;
						div.style.left = this.x + "px";
						div.style.top = this.y + "px";
					}

					var food = new Food(40, 40, "pink");
					food.init(map);

				}, 1);

			})();
		</script>
	</body>

</html>